package Demo02;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.*;


// 线程创建方式3，实现 callable 接口
public class ThreadCallable implements Callable<Boolean> {
    private String url;  // 网络图片地址
    private String name; // 保存的图片名字

    public ThreadCallable(String url,String name){
        this.url = url;
        this.name = name;
    }

    // 线程下载图片的方法
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);

        System.out.println("下载了文件名为：" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadCallable t1 = new ThreadCallable("http://wx3.sinaimg.cn/large/00869HDlly1gky8a0hgt7j31hc0u04qp.jpg","1.jpg");
        ThreadCallable t2= new ThreadCallable("http://wx4.sinaimg.cn/large/00869HDlly1gky85yncr6j30u00u0hdu.jpg","2.jpg");
        ThreadCallable t3 = new ThreadCallable("http://wx2.sinaimg.cn/large/00869HDlly1gky7cczh9fj30u00vxgx6.jpg","3.jpg");

        // 4.创建只想服务：
        ExecutorService ser = Executors.newFixedThreadPool(3);

        // 5.提交执行：
        Future<Boolean> result1 = ser.submit(t1);
        Future<Boolean> result2 = ser.submit(t2);
        Future<Boolean> result3 = ser.submit(t3);

        // 6.获取结：
        boolean res1 = result1.get();
        boolean res2 = result2.get();
        boolean res3 = result3.get();

        System.out.println(res1);
        System.out.println(res2);
        System.out.println(res3);

        // 7.关闭服务:
        ser.shutdownNow();
    }
}


class WebDownloader{
    // 下载方法
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO 异常，downloader 方法出现问题");
        }
    }
}